import * as crypto from 'crypto-js';
import * as Base64 from 'js-base64';

import { OssCredentialsModel } from './../../core/api/models/oss-config-model';



// 计算签名。
function computeSignature(accessKeySecret: string, canonicalString: string) {
    return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret));
}

const date = new Date();
date.setHours(date.getHours() + 1);
const policyText = {
    expiration: date.toISOString(), // 设置policy过期时间。
    conditions: [
        // 限制上传大小。
        ["content-length-range", 0, 1024 * 1024 * 1024],
    ],
};

export async function getUploadParams(credentials: OssCredentialsModel) {
    const policy = Base64.encode(JSON.stringify(policyText)) // policy必须为base64的string。
    const signature = computeSignature(credentials.accessKeySecret, policy)
    const formData = {
        OSSAccessKeyId: credentials.accessKeyId,
        signature,
        policy,
        'x-oss-security-token': credentials.securityToken
    }
    return formData;
}